﻿using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Zhp.Common.Appsetting;
using Zhp.Common.Helper;

namespace Zhp.Cache
{
    public static class CacheManager
    {
        public static IServiceCollection AddCacheManager(this IServiceCollection services)
        {
            var cache = services.GetOptions<CacheOptions>();
            if (cache.UseRedis)
            {
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = cache.RedisSettings.Address;
                    options.InstanceName = cache.RedisSettings.InstanceName;
                });

                // 获取Redis配置信息
                var redisConfiguration = ConfigurationOptions.Parse(cache.RedisSettings.Address);
                redisConfiguration.AbortOnConnectFail = false; // 避免在初始化时出现故障
                redisConfiguration.AllowAdmin = true; // 需要允许使用ADMIN命令才能清除所有缓存
                redisConfiguration.DefaultDatabase = cache.RedisSettings.Db;
                redisConfiguration.ChannelPrefix = RedisChannel.Pattern(cache.RedisSettings.InstanceName);

                var redisConnect = ConnectionMultiplexer.Connect(redisConfiguration);
                var dataBase = redisConnect.GetDatabase(cache.RedisSettings.Db);
                services.AddSingleton(dataBase);
                services.AddSingleton<ICacheService, RedisCacheService>();

                ConsoleHelper.WriteLine($"Redis服务注入成功", ConsoleColor.Green);
            }
            else
            {
                services.AddDistributedMemoryCache();
                services.AddSingleton<ICacheService, MemoryCacheService>();
                ConsoleHelper.WriteLine($"内存缓存服务注入成功", ConsoleColor.Green);
            }

            return services;
        }
    }
}
